<template>
  <!-- 博客评论 -->
  <div class="blog-comment-container">
    <div class="title">发布评论</div>
    <MessageArea
      title="评论列表"
      :subTitle="`(${data.total})`"
      :list="data.rows"
      :isListLoading="isLoading"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { getComments, postComment } from "@/api/blog.js";

export default {
  mixins: [fetchData({ total: 0, rows: [] })],
  components: {
    MessageArea,
  },
  data() {
    return {
      page: 1,
      limit: 10,
    };
  },
  created() {
    this.$bus.$on("mainScroll", this.handleScroll);
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.handleScroll);
  },
  computed: {
    // 是否已经加载完所有评论
    hasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods: {
    async fetchData() {
      const id = this.$route.params.id;
      const resp = await getComments(id, this.page, this.limit);
      // console.log("当前id:", id);
      const result = resp.rows.filter((item) => id === item.blog.id);
      const data = {
        rows: result,
        total: result.length,
      };
      console.log("结果:", data);
      return data;
    },
    async handleSubmit(formData, callback) {
      // callback是一个回调函数, 需要在表单提交后执行
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });
      this.data.rows.unshift(resp); // 方法unshift用于将数据添加至数组开头
      this.data.total++; // 评论总数加一
      callback("评论成功"); // 告诉子组件, 我这边处理完了, 你继续
    },
    // 加载"下一页"的评论
    async fetchMore() {
      if (!this.hasMore) {
        // 没有更多评论了
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData(); // 再次获取评论数据
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows); // 将新请求的评论数据添加到原评论数据列表中[concat是拼接数组]
      this.isLoading = false;
    },
    // 鼠标滚动事件处理函数
    handleScroll(dom) {
      if (this.isLoading || !dom) {
        // 目前正在加载更多评论
        return;
      }
      const range = 100; // 底部误差范围, 在这个范围内都算到达底部
      const top = dom.scrollTop;
      const h = dom.clientHeight;
      const scrollH = dom.scrollHeight;
      if (Math.abs(scrollH - top - h) <= range) {
        // abs是求绝对值
        this.fetchMore();
        console.log("到达底部");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.blog-comment-container {
  .title {
    font-size: 18px;
    font-weight: bold;
    margin: 15px 0;
  }
}
</style>
